package com.open.api.wechat.common;


import com.open.api.wechat.utils.HttpUtil;
import com.open.api.wechat.utils.JsonUtil;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;

/**
 * @author : zhaoxuan
 * @date : 2021/6/30 23:34
 * @description : WeChatClient
 * @version : 1.0
 */
public class WeChatClient {

    public static <T extends WeChatCommonResponse> T execute(WeChatCommonRequest<T> request) {
        String result = "";
        if (HttpMethod.GET == request.getMethod()) {
            result = HttpUtil.get(request.getUrl());
        }
        if (HttpMethod.POST == request.getMethod()) {
            result = HttpUtil.post(request.getUrl(), request.getBody());
        }
        return JsonUtil.parseObject(StringUtils.isNotBlank(result) ? result : WeChatCommonResponse.DEFAULT_TIME_OUT_RESPONSE, request.getResponse());
    }

    public static <T extends WeChatCommonResponse> T execute(WeChatCommonRequest<T> request, String accessToken) {
        String result = "";
        if (HttpMethod.GET == request.getMethod()) {
            result = HttpUtil.get(request.getUrl(accessToken));
        }
        if (HttpMethod.POST == request.getMethod()) {
            result = HttpUtil.post(request.getUrl(accessToken), request.getBody());
        }
        return JsonUtil.parseObject(StringUtils.isNotBlank(result) ? result : WeChatCommonResponse.DEFAULT_TIME_OUT_RESPONSE, request.getResponse());
    }

    public static Response executeFileBytes(WeChatCommonRequest request) {
        Response result = null;
        if (HttpMethod.GET == request.getMethod()) {
            result = HttpUtil.getFile(request.getUrl());
        }
        if (HttpMethod.POST == request.getMethod()) {
            result = HttpUtil.postFile(request.getUrl(), request.getBody());
        }
        return result;
    }

    public static Response executeFileBytes(WeChatCommonRequest request, String accessToken) {
        Response result = null;
        if (HttpMethod.GET == request.getMethod()) {
            result = HttpUtil.getFile(request.getUrl(accessToken));
        }
        if (HttpMethod.POST == request.getMethod()) {
            result = HttpUtil.postFile(request.getUrl(accessToken), request.getBody());
        }
        return result;
    }

}
